package servlet;

import model.User;
import model.Product;
import model.Order;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import service.OrderService;
import service.ProductService;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@WebServlet(name = "goods_publish", urlPatterns = "/goods_publish")
public class GoodsPublishServlet extends HttpServlet {
    private ProductService pService = new ProductService();
    private OrderService oService = new OrderService();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("开始处理商品添加请求...");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(10 * 1024 * 1024); // 限制总上传大小为10MB
        upload.setFileSizeMax(2 * 1024 * 1024); // 限制单个文件大小为2MB
        try {
            List<FileItem> list = upload.parseRequest(request);//HTTP请求里所有的表单项与上传的文件
            Product p = new Product();
            User u = (User) request.getSession().getAttribute("user");
            if (u == null) {
                request.setAttribute("failgas", "请先登录！");
                request.getRequestDispatcher("/user_login.jsp").forward(request, response);
                return;
            }
            p.setReceiver_id(u.getId());//获取用户id
            p.setCreate_time(new Date());//获取商品添加时间
            p.setStatus(false);
            for(FileItem item:list) {//将list集合中的每一个元素依次赋值给item
                if(item.isFormField()) {//处理普通表单数据
                    String fieldName = item.getFieldName();
                    String value = item.getString("utf-8");
                    System.out.println("处理表单字段: " + fieldName + " = " + value);

                    switch(fieldName) {
                        case "goodsName":
                            p.setName(value);
                            break;
                        case "goodsDetail":
                            p.setDetail(value);
                            break;
                        case "pickupAddress":
                            p.setPickup_address(value);
                            break;
                        case "proxyAddress":
                            p.setProxy_address(value);
                            break;
                        case "phoneNumber":
                            p.setPhone_number(value);
                            break;
                        case "categoryId":
                            p.setCategoryid(Integer.parseInt(value));
                            break;
                        case "price":
                            p.setPrice(Float.parseFloat(value));
                            break;
                        case "status":
                            p.setStatus("1".equals(value));
                            break;
                    }
                } else {//处理文件上传
                    if(item.getInputStream().available()<=0)continue;
                    String fileName = item.getName();
                    fileName = fileName.substring(fileName.lastIndexOf("."));
                    fileName = "/"+new Date().getTime()+fileName;
                    String path = this.getServletContext().getRealPath("/picture")+fileName;
                    System.out.println("处理文件上传: " + path);


                    InputStream in = item.getInputStream();
                    FileOutputStream out = new FileOutputStream(path);
                    byte[] buffer = new byte[1024];
                    int len=0;
                    while( (len=in.read(buffer))>0 ) {
                        out.write(buffer);
                    }
                    in.close();
                    out.close();
                    item.delete();

                    if("cover".equals(item.getFieldName())) {
                        p.setCover("/picture"+fileName);
                        System.out.println("设置商品详情图片: /picture" + fileName);
                    }
                }
            }

            try {
                System.out.println("准备插入商品数据到数据库...");
                System.out.println("商品信息: " + p.toString());
                pService.insert(p);
                //每发布一个商品就生成一个订单
                Order o = new Order();
                o.setStatus(true);
                o.setCode(String.valueOf(System.currentTimeMillis()) + u.getUsername());
                o.setProduct_id(p.getId());
                o.setPrice(p.getPrice());
                o.setReceiver_id(u.getId());
                o.setProxy_id(-1);//默认接单id为-1
                o.setPhone_number(p.getPhone_number());
                o.setProduct(p);
                oService.insertOrder(o);
                //更新goodsList数据
                List<Product> goodslist= pService.GetAllOnSaleProduct();
                this.getServletContext().removeAttribute("goodsList");
                this.getServletContext().setAttribute("goodsList",goodslist);
                System.out.println("商品数据插入成功！");
                request.setAttribute("gas", "物品发布成功！");
                request.getRequestDispatcher("/goods_publish.jsp").forward(request, response);
//                response.sendRedirect(request.getContextPath() + "/goods_list.jsp");//重定向到goods_list.jap路径
            } catch (Exception e) {
                System.err.println("插入商品数据时发生错误: " + e.getMessage());
                e.printStackTrace();
                request.setAttribute("failgas", "添加商品失败：" + e.getMessage());
                request.getRequestDispatcher("/goods_publish.jsp").forward(request, response);
            }

        } catch (FileUploadException e) {
            System.err.println("文件上传失败: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("failgas", "文件上传失败：" + e.getMessage());
            request.getRequestDispatcher("/goods_publish.jsp").forward(request, response);
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

}